import 'package:flutter/material.dart';
import '../../models/user_model.dart';
import '../../models/chat_model.dart';
import '../../utils/cached_image_widget.dart';
import 'chat_page.dart';

class ChatListPage extends StatefulWidget {
  const ChatListPage({super.key});

  @override
  State<ChatListPage> createState() => _ChatListPageState();
}

class _ChatListPageState extends State<ChatListPage> {
  // 模拟聊天会话数据
  final List<ChatSession> _chatSessions = [
    ChatSession(
      id: '1',
      userId: 'current_user',
      otherUserId: '1',
      otherUsername: '张三',
      otherUserAvatar: '',
      lastMessage: '你好，我想咨询一下React开发的问题',
      lastMessageTime: DateTime.now().subtract(const Duration(minutes: 5)),
      unreadCount: 2,
      isOnline: true,
    ),
    ChatSession(
      id: '2',
      userId: 'current_user',
      otherUserId: '2',
      otherUsername: '李四',
      otherUserAvatar: '',
      lastMessage: '好的，我们明天见面详谈',
      lastMessageTime: DateTime.now().subtract(const Duration(hours: 2)),
      unreadCount: 0,
      isOnline: false,
    ),
    ChatSession(
      id: '3',
      userId: 'current_user',
      otherUserId: '3',
      otherUsername: '王五',
      otherUserAvatar: '',
      lastMessage: '项目进展如何？',
      lastMessageTime: DateTime.now().subtract(const Duration(days: 1)),
      unreadCount: 1,
      isOnline: true,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('聊天'),
        backgroundColor: Theme.of(context).primaryColor,
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              // 搜索聊天记录
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('搜索功能开发中...')),
              );
            },
          ),
          IconButton(
            icon: const Icon(Icons.more_vert),
            onPressed: () {
              // 更多选项
              _showMoreOptions();
            },
          ),
        ],
      ),
      body: _chatSessions.isEmpty
          ? _buildEmptyState()
          : ListView.builder(
              itemCount: _chatSessions.length,
              itemBuilder: (context, index) {
                final session = _chatSessions[index];
                return _buildChatSessionItem(session);
              },
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 发起新聊天
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('发起新聊天功能开发中...')),
          );
        },
        backgroundColor: Theme.of(context).primaryColor,
        child: const Icon(Icons.chat, color: Colors.white),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.chat_bubble_outline,
            size: 80,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            '暂无聊天记录',
            style: TextStyle(
              fontSize: 18,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            '开始与其他人聊天吧',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildChatSessionItem(ChatSession session) {
    return ListTile(
      leading: Stack(
        children: [
          CachedAvatarWidget(
            avatarUrl: session.otherUserAvatar,
            size: 50,
          ),
          if (session.isOnline)
            Positioned(
              right: 0,
              bottom: 0,
              child: Container(
                width: 12,
                height: 12,
                decoration: BoxDecoration(
                  color: Colors.green,
                  shape: BoxShape.circle,
                  border: Border.all(color: Colors.white, width: 2),
                ),
              ),
            ),
        ],
      ),
      title: Row(
        children: [
          Expanded(
            child: Text(
              session.otherUsername,
              style: const TextStyle(
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          Text(
            _formatTime(session.lastMessageTime),
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
      subtitle: Row(
        children: [
          Expanded(
            child: Text(
              session.lastMessage,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color:
                    session.unreadCount > 0 ? Colors.black87 : Colors.grey[600],
                fontWeight: session.unreadCount > 0
                    ? FontWeight.w500
                    : FontWeight.normal,
              ),
            ),
          ),
          if (session.unreadCount > 0) ...[
            const SizedBox(width: 8),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(10),
              ),
              constraints: const BoxConstraints(
                minWidth: 16,
                minHeight: 16,
              ),
              child: Text(
                session.unreadCount > 99
                    ? '99+'
                    : session.unreadCount.toString(),
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 10,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ],
        ],
      ),
      onTap: () {
        // 跳转到聊天页面
        final targetUser = UserModel(
          id: session.otherUserId,
          username: session.otherUsername,
          email: '',
          avatar: session.otherUserAvatar,
          location: '',
          bio: '',
          skills: [],
          certifications: [],
          isOnline: session.isOnline,
          createdAt: DateTime.now(),
        );

        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => ChatPage(targetUser: targetUser),
          ),
        );
      },
      onLongPress: () {
        _showChatOptions(session);
      },
    );
  }

  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays}天前';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}小时前';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}分钟前';
    } else {
      return '刚刚';
    }
  }

  void _showMoreOptions() {
    showModalBottomSheet(
      context: context,
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ListTile(
            leading: const Icon(Icons.search),
            title: const Text('搜索聊天记录'),
            onTap: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('搜索功能开发中...')),
              );
            },
          ),
          ListTile(
            leading: const Icon(Icons.delete_sweep),
            title: const Text('清空聊天记录'),
            onTap: () {
              Navigator.pop(context);
              _showClearChatConfirm();
            },
          ),
          ListTile(
            leading: const Icon(Icons.settings),
            title: const Text('聊天设置'),
            onTap: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('聊天设置功能开发中...')),
              );
            },
          ),
        ],
      ),
    );
  }

  void _showChatOptions(ChatSession session) {
    showModalBottomSheet(
      context: context,
      builder: (context) => Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ListTile(
            leading: const Icon(Icons.pin_drop),
            title: const Text('置顶聊天'),
            onTap: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('置顶功能开发中...')),
              );
            },
          ),
          ListTile(
            leading: const Icon(Icons.notifications_off),
            title: const Text('免打扰'),
            onTap: () {
              Navigator.pop(context);
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('免打扰功能开发中...')),
              );
            },
          ),
          ListTile(
            leading: const Icon(Icons.delete),
            title: const Text('删除聊天'),
            onTap: () {
              Navigator.pop(context);
              _showDeleteChatConfirm(session);
            },
          ),
        ],
      ),
    );
  }

  void _showClearChatConfirm() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清空聊天记录'),
        content: const Text('确定要清空所有聊天记录吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              setState(() {
                _chatSessions.clear();
              });
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('聊天记录已清空')),
              );
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showDeleteChatConfirm(ChatSession session) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除聊天'),
        content: Text('确定要删除与 ${session.otherUsername} 的聊天记录吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              setState(() {
                _chatSessions.remove(session);
              });
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('聊天记录已删除')),
              );
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
}
